﻿using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace TechFreak.uapman
{
    /// <summary>
    /// Utility methods for Image conversion
    /// </summary>
    internal static class ImageConverters
    {
        /// <summary>
        /// Converts an <see cref="Image"/> to a <see cref="byte"/> array.
        /// </summary>
        /// <param name="imageToConvert"><see cref="Image"/> to convert</param>
        /// <param name="formatOfImage">Image format</param>
        /// <returns></returns>
        internal static byte[] ConvertImageToByteArray(Image imageToConvert, ImageFormat formatOfImage)
        {
            using (var ms = new MemoryStream())
            {
                imageToConvert.Save(ms, formatOfImage);
                return ms.ToArray();
            }
        }

        /// <summary>
        /// Converts a <see cref="byte"/> array to an <see cref="Image"/>
        /// </summary>
        /// <param name="byteArray"><see cref="byte"/> Array to convert</param>
        /// <returns><see cref="Image"/></returns>
        internal static Image ConvertByteArrayToImage(byte[] byteArray)
        {
            if (byteArray != null)
            {
                var ms = new MemoryStream(byteArray, 0, byteArray.Length);
                ms.Write(byteArray, 0, byteArray.Length);
                return Image.FromStream(ms, true);
            }
            return null;
        }
    }
}
